package com.woohua.thread.lock;


/***
 * @title Worker
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/10 14:44
 **/
public class Worker implements Runnable {

    private final Object lockX;

    private final Object lockY;

    public Worker(Object lockX, Object lockY) {
        // 解决死锁 ： 对锁顺序排序
        int result = lockX.toString().compareTo(lockY.toString());

        this.lockX = result >= 0 ? lockX : lockY;
        this.lockY = result >= 0 ? lockY : lockX;
    }

    @Override
    public void run() {
        synchronized (lockX) {
            System.out.println("lockX current lock" + Thread.currentThread().getName());
            //休眠一会，等待另外一个线程获取到lockY
            sleep(2000);
            System.out.println(Thread.currentThread().getName() + " get lock " + lockX);

            synchronized (lockY) {
                System.out.println("lockY current lock" + Thread.currentThread().getName());
                //这一步由于发生了死锁永远不会执行
                System.out.println(Thread.currentThread().getName() + " get lock " + lockY);
            }
        }
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
